package com.ky.pro.java.sharding.ecommerce;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@Slf4j
public class OrderSchemaGenerator {


    public static void main(String[] args) throws SQLException, ClassNotFoundException {

        Class.forName("com.mysql.cj.jdbc.Driver");

        String url = "jdbc:mysql://127.0.0.1:3306/ecommerce" +
                "?useUnicode=true&characterEncoding=utf-8&useSSL=false" +
                "&allowLoadLocalInfile=true" +
                "&logger=Slf4JLogger&profileSQL=true";
        String user = "kevin";
        String password = "123456";

        int dbCnt = 2;
        int tableCntPerDb = 16;

        Connection connection = DriverManager.getConnection(url, user, password);

        String dbDdl = "create database ecommerce_? character set utf8;";
        String tableDdl = "create table ecommerce_?.t_com_order_?\n" +
                "(\n" +
                "   id                   bigint not null comment '订单ID',\n" +
                "   user_id              bigint not null comment '用户ID',\n" +
                "   order_no             bigint not null comment '订单号',\n" +
                "   order_status         int comment '订单状态，1 - 待支付；2 - 已支付；3 - 已完成； 4 - 已取消',\n" +
                "   order_remark         varchar(1024) comment '订单备注',\n" +
                "   del_status           bool not null comment '删除标志',\n" +
                "   create_time          datetime not null comment '创建时间',\n" +
                "   update_time          datetime not null comment '更新时间',\n" +
                "   version              int not null comment '版本号',\n" +
                "   primary key (id)\n" +
                ") engine=INNODB;";
        String commentDdl = "alter table ecommerce_?.t_com_order_? comment '订单信息表';";

        PreparedStatement dbPs = connection.prepareStatement(dbDdl);
        PreparedStatement tablePs = connection.prepareStatement(tableDdl);
        PreparedStatement commentPs = connection.prepareStatement(commentDdl);

        for (int i = 0; i < dbCnt; i++) {
            dbPs.setInt(1, i);
            dbPs.addBatch();
            for (int j = 0; j < tableCntPerDb; j++) {
                tablePs.setInt(1, i);
                tablePs.setInt(2, j);
                tablePs.addBatch();
                commentPs.setInt(1, i);
                commentPs.setInt(2, j);
                commentPs.addBatch();
            }
        }

        dbPs.executeBatch();
        tablePs.executeBatch();
        commentPs.executeBatch();

    }


}
